import { useEffect, useState } from 'react';
import { Button, Flex, Input } from 'antd';
import { SPACE } from '@/constants/themeConstant.js';
import { DeleteOutlined } from '@ant-design/icons';

/**
 * 键值对编辑器
 *
 * @param {object} props 组件属性
 * @param {string} props.keyName 键名称
 * @param {string} props.valueName 值名称
 * @param {string} props.keyTitle 键标题
 * @param {string} props.valueTitle 值标题
 * @param {array} props.pairs 初始键值对数组
 * @param {function} props.onChange 键值对变化回调函数
 */
export default function KeyValueEditor(props) {
  const { onChange } = props;
  const [pairs, setPairs] = useState([]);
  const keyName = props?.keyName || 'key';
  const valueName = props?.valueName || 'value';
  const keyTitle = props?.keyTitle || '键';
  const valueTitle = props?.valueTitle || '值';

  useEffect(() => {
    if (Array.isArray(props.pairs)) {
      setPairs(props.pairs);
    }
  }, [props.pairs]);

  function handleChange(pairs) {
    onChange && onChange(pairs);
  }

  /**
   * 添加新的键值对
   */
  const addPair = () => {
    const newPairs = [...pairs, { [keyName]: '', [valueName]: '' }];
    setPairs(newPairs);
    handleChange(newPairs);
  };

  /**
   * 更新指定索引的键值对
   *
   * @param {number} index 索引
   * @param {string} field 字段
   * @param {string} value 值
   */
  const updatePair = (index, field, value) => {
    const newPairs = [...pairs];
    newPairs[index][field] = value;
    setPairs(newPairs);
    handleChange(newPairs);
  };

  /**
   * 删除指定索引的键值对
   *
   * @param index 索引
   */
  const removePair = (index) => {
    const newPairs = [...pairs];
    newPairs.splice(index, 1);
    setPairs(newPairs);
    handleChange(newPairs);
  };

  return (
    <Flex vertical gap={SPACE}>
      {pairs.map((pair, index) => {
        return (
          <Flex key={index} gap={SPACE}>
            <Input
              value={pair[keyName]}
              onChange={(e) => updatePair(index, keyName, e.target.value)}
              placeholder={`请输入${keyTitle}`}
            />
            <Input
              value={pair[valueName]}
              onChange={(e) => updatePair(index, valueName, e.target.value)}
              placeholder={`请输入${valueTitle}`}
            />
            <Button danger onClick={() => removePair(index)}>
              <DeleteOutlined />
            </Button>
          </Flex>
        );
      })}
      <Button type="primary" onClick={addPair}>
        添加{keyTitle}和{valueTitle}
      </Button>
    </Flex>
  );
}
